package cn.dankal.flyaudio.login;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import androidx.lifecycle.Observer;
import api.ChatServiceFactory;
import api.UserServiceFactory;
import butterknife.BindView;
import butterknife.OnClick;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.RegisterJpushEntity;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.business.eventbus.OFFLoginEvent;
import cn.dankal.flyaudio.contract.LoginContractHelper;
import cn.dankal.flyaudio.database.UserEntry;
import cn.dankal.flyaudio.model.FlyUser;
import cn.dankal.flyaudio.wxapi.WXEntryActivity;
import cn.dankal.basiclib.pojo.UserInfoBean;
import cn.dankal.basiclib.pojo.UserResponseBody;
import cn.dankal.basiclib.protocol.MainProtocol;
import cn.dankal.basiclib.protocol.LoginProtocol;
import cn.dankal.basiclib.rx.AbstractDialogSubscriber;
import cn.dankal.basiclib.util.AppUtils;
import cn.dankal.basiclib.util.StringUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.business.Constants;
import cn.dankal.flyaudio.R;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

@Route(path = LoginProtocol.LOGIN)
public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_phone_num)
    EditText mEtPhoneNum;
    @BindView(R.id.et_passwd)
    EditText mEtPasswd;
    private long exitTime;
    private IWXAPI iwxapi;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initComponents() {
        iwxapi = WXAPIFactory.createWXAPI(this, WXEntryActivity.WX_APP_ID, true);
        iwxapi.registerApp(WXEntryActivity.WX_APP_ID);
        EventBus.getDefault().register(this);
        LiveEventBus.get("wx_login", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                LoginContractHelper.sendLoginBoardCast(LoginActivity.this);
                saveCar();
                getPassword();
            }
        });

    }


    @OnClick({R.id.iv_onback, R.id.bt_login, R.id.tv_register, R.id.tv_forget, R.id.iv_wechat, R.id.tv_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_onback:
                finish();
                break;
            case R.id.bt_login:
                String account = mEtPhoneNum.getText().toString();
                String pass = mEtPasswd.getText().toString();
                if (TextUtils.isEmpty(account) && TextUtils.isEmpty(pass)) {
                    ToastUtils.showShort("请输入账号和密码");
                    return;
                }
                if (TextUtils.isEmpty(account)) {
                    ToastUtils.showShort("请输入账号");
                    return;
                }
                if (TextUtils.isEmpty(pass)) {
                    ToastUtils.showShort("请输入密码");
                    return;
                }
                if (!StringUtil.checkPhone(account)) {
                    ToastUtils.showShort("请输入正确的手机号码");
                    return;
                }
                if (!StringUtil.checkPasswd(pass) || pass.length() < 6) {
                    ToastUtils.showShort("请输入密码，6-20数字、字母、符号，不允许特殊符号`'\\“ 空格");
                    return;
                }
                accountLogin(account, pass);
                break;
            case R.id.tv_forget:
                ARouter.getInstance().build(LoginProtocol.FORGET_PASSWD)
                        .withString(Constants.TYPE, Constants.TYPE_FORGET_PASS).navigation();
                break;

            case R.id.tv_register:
                ARouter.getInstance().build(LoginProtocol.FORGET_PASSWD)
                        .withString(Constants.TYPE, Constants.TYPE_REGISTER).navigation();

                break;
            case R.id.iv_wechat:
                //跳往 WXEntryActivity
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "dankal-android-login";
                iwxapi.sendReq(req);
                // finish();
                break;

            case R.id.tv_agreement:
                startActivity(new Intent(this, LoginAgreementActivity.class));
                break;
            default:
        }
    }

    /**
     * 账号登录
     *
     * @param pass
     */
    private void accountLogin(String account, String pass) {
        Map<String, String> map = new HashMap(2);
        map.put("phone", account);
        map.put("password", pass);
        showLoadingDialog();
        UserServiceFactory.login(map)
                .subscribe(new AbstractDialogSubscriber<UserInfoBean>(this) {
                    @Override
                    public void onNext(UserInfoBean userInfoBean) {
                        DankalApplication.setLogin(true);
                        Log.d("LoginActivity","accessToken:"+userInfoBean.getAccessToken());
                        UserResponseBody userResponseBody = new UserResponseBody();
                        UserResponseBody.TokenBean tokenBean = new UserResponseBody.TokenBean();
                        tokenBean.token = userInfoBean.getAccessToken();
                        tokenBean.fgToken = userInfoBean.getFgToken();
                        userResponseBody.setToken(tokenBean);
                        userResponseBody.setUserInfo(userInfoBean);
                        DKUserManager.saveUserInfo(userResponseBody);
                        DKUserManager.updateUserInfo(userInfoBean);
                        LoginContractHelper.sendLoginBoardCast(LoginActivity.this);
                        saveCar();
                        getPassword();
                    }
                });
    }

    private void getPassword() {
        showLoadingDialog();
        ChatServiceFactory.initialization()
                .subscribe(new AbstractSubscriber<BaseResponse<RegisterJpushEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<RegisterJpushEntity> registerJpushEntityBaseResponse) {
                        JMessageClient.login(registerJpushEntityBaseResponse.getData().getUser().getUsername(), registerJpushEntityBaseResponse.getData().getUser().getPassword(), new BasicCallback() {
                            @Override
                            public void gotResult(int responseCode, String LoginDesc) {
                                dismissLoadingDialog();
                                if (responseCode == 0) {
                                    LoginContractHelper.sendLoginBoardCast(LoginActivity.this);
                                    UserInfo userInfo = JMessageClient.getMyInfo();
                                    String username = userInfo.getUserName();
                                    String appKey = userInfo.getAppKey();
                                    userInfo.setNickname(DKUserManager.getUserInfo().getName());
                                    userInfo.setUserExtras("phone", DKUserManager.getUserInfo().getPhone());
                                    new Thread(() -> {
                                        try {
                                            if (!cn.dankal.flyaudio.friend.pickimage.StringUtil.isEmpty(DKUserManager.getUserInfo().getAvatar())) {
                                                File mFile = Glide.with(LoginActivity.this).asFile().load(PicUtils.getUrl(DKUserManager.getUserInfo().getAvatar())).submit().get();
                                                JMessageClient.updateUserAvatar(mFile, new BasicCallback() {
                                                    @Override
                                                    public void gotResult(int i, String s) {

                                                    }
                                                });
                                            }
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        } catch (ExecutionException e) {
                                            e.printStackTrace();
                                        }
                                    }).start();
                                    JMessageClient.updateMyInfo(UserInfo.Field.nickname, userInfo, new BasicCallback() {
                                        @Override
                                        public void gotResult(int i, String s) {

                                        }
                                    });
                                    JMessageClient.updateMyInfo(UserInfo.Field.extras, userInfo, new BasicCallback() {
                                        @Override
                                        public void gotResult(int i, String s) {

                                        }
                                    });
                                    UserEntry user = UserEntry.getUser(username, appKey);
                                    if (null == user) {
                                        user = new UserEntry(username, appKey);
                                        user.save();
                                    }
                                    ARouter.getInstance().build(MainProtocol.MAIN).navigation();
                                    finish();
                                } else {
                                    Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
    }

    private void loginJPush() {
        ChatServiceFactory.initialization()
                .subscribe(new AbstractSubscriber<BaseResponse<RegisterJpushEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<RegisterJpushEntity> registerJpushEntityBaseResponse) {
                        JMessageClient.login(registerJpushEntityBaseResponse.getData().getUser().getUsername(), registerJpushEntityBaseResponse.getData().getUser().getPassword(), new BasicCallback() {
                            @Override
                            public void gotResult(int responseCode, String LoginDesc) {
                                dismissLoadingDialog();
                                if (responseCode == 0) {
                                    UserInfo userInfo = JMessageClient.getMyInfo();
                                    String username = userInfo.getUserName();
                                    String appKey = userInfo.getAppKey();
                                    UserEntry user = UserEntry.getUser(username, appKey);
                                    if (null == user) {
                                        user = new UserEntry(username, appKey);
                                        user.save();
                                    }
                                    ARouter.getInstance().build(MainProtocol.MAIN).navigation();
                                    finish();
                                } else {
                                    Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
    }

    private void saveCar() {
        FlyUser flyUser = new FlyUser();
        String id = DKUserManager.getUserInfo().getId();
        flyUser.setToken(DKUserManager.getUserToken().getFgToken());
        flyUser.setUuid(DKUserManager.getUserInfo().getId());
        LoginContractHelper.saveLoginUserInfo(LoginActivity.this, flyUser);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtils.showShort("再按一次退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                AppUtils.finishAllActivities();
                finish();
               /* new Handler().postDelayed(() -> {
                    try {
                        // 杀死该应用进程
                        android.os.Process.killProcess(android.os.Process.myPid());
                        System.exit(0);
                    } catch (Exception e) {
                    }
                }, 500);*/
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (iwxapi != null) {
            iwxapi.unregisterApp();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMessage(OFFLoginEvent offLoginEvent) {
        finish();
    }
}
